package com.konsung.ksdc.manager.saleservice;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.ReplyNetBean;
import com.konsung.ksdc.bean.netbean.SaleServiceNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.AfterSaleEvaluate;
import com.konsung.ksdc.common.widget.ConfirmPopupWindow;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;
import com.konsung.ksdc.manager.machine.NetPicActivity;
import com.squareup.picasso.Picasso;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 售后详情页面
 * Created by Administrator on 2016/3/24 0024.
 */
public class SaleServiceDetailActivity extends BaseActivity {
    public static final String SALE_SERVICE_NETBEAN = "sale_detail_reply";
    public static final String SALE_SERVICE_DATE = "sale_detail_date";
    public static final String SALE_SERVICE_ID = "sale_service_id";

    private static final int MSG_SERVER_ERROR = 2; // 访问服务器失败
    private static final int MSG_SALE_SERVICE_DATA = 3; // 加载售后信息成功
    @Bind(R.id.tab_tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tv_problem_desc)
    TextView tvProblemDesc;
    @Bind(R.id.ll_photo_container)
    LinearLayout llPhotoContainer;
    @Bind(R.id.lv_problem_message_list)
    ListView lvProblemMessageList;
    @Bind(R.id.tv_mac_name)
    TextView tvMacName;
    @Bind(R.id.tv_mac_sealnum)
    TextView tvMacSealnum;
    @Bind(R.id.btn_confirm_resolved)
    Button btnConfirmResolved;
    @Bind(R.id.tv_evaluate)
    TextView tvEvaluate;
    @Bind(R.id.tv_create_date)
    TextView tvCreateData;

    private SaleServiceNetBean saleServiceNetBean;
    private AfterSaleEvaluate afterSaleEvaluate;
    private ConfirmPopupWindow popupWindow;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AfterSaleEvaluate.EVALUATED:
                    finish();
                    break;
                case MSG_SERVER_ERROR:
                    ToastUtils.toastContent(MyApplication.getContext(), MyApplication
                            .getContext().getString(R.string.chat_unconnect));
                    break;
                case MSG_SALE_SERVICE_DATA:
                    initView();
                    showData();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sale_detail);
        ButterKnife.bind(this);

        initData();
        initEvent();
    }

    /**
     * 初始化售后详情界面
     */
    private void initView() {
        String serviceState = saleServiceNetBean.getServiceState();
        switch (serviceState) {
            case SaleServiceNetBean.STATUS_UNDISPOSED:
                btnConfirmResolved.setVisibility(View.VISIBLE);
                tvEvaluate.setVisibility(View.GONE);
                break;
            case SaleServiceNetBean.STATUS_DISPOSING:
                btnConfirmResolved.setVisibility(View.VISIBLE);
                tvEvaluate.setVisibility(View.GONE);
                break;
            case SaleServiceNetBean.STATUS_DISPOSED:
                btnConfirmResolved.setVisibility(View.VISIBLE);
                tvEvaluate.setVisibility(View.GONE);
                break;
            case SaleServiceNetBean.STATUS_USER_CONFIRM:
                btnConfirmResolved.setVisibility(View.GONE);
                tvEvaluate.setVisibility(View.VISIBLE);
                break;
            case SaleServiceNetBean.STATUS_CLOSED:
                btnConfirmResolved.setVisibility(View.GONE);
                tvEvaluate.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_sale_service_detail);
    }

    /**
     * 初始化售后页面点击事件
     */
    private void initEvent() {
        btnConfirmResolved.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow = new ConfirmPopupWindow(SaleServiceDetailActivity.this,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                RequestUtils.doSaleConfirm(saleServiceNetBean.getId(), new
                                        RequestCallback() {
                                            @Override
                                            public void onError(Call call, Exception e) {
                                            }

                                            @Override
                                            public void onResponse(ResponseBean responseBean) {
                                                if (Constants.REQUEST_OK.equals(responseBean
                                                        .getResultCode())) {
                                                    btnConfirmResolved.setVisibility(View.GONE);
                                                    tvEvaluate.setVisibility(View.VISIBLE);
                                                    popupEvaluate();
                                                }
                                            }
                                        });
                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                            }
                        });
                popupWindow.setTips(getString(R.string.confirm_after_sale_problem));
                popupWindow.setTitle(getString(R.string.after_sale_manage));
                popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            }
        });
        tvEvaluate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupEvaluate();
            }
        });
    }

    /**
     * 弹出售后评价框
     */
    private void popupEvaluate() {
        afterSaleEvaluate = new AfterSaleEvaluate(SaleServiceDetailActivity.this, handler,
                btnConfirmResolved, saleServiceNetBean.getId());
        afterSaleEvaluate.openWindow();
    }

    /**
     * 初始化售后数据
     */
    private void initData() {
        tvTitle.setText(R.string.title_activity_after_sell);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        String serviceId = getIntent().getStringExtra(SALE_SERVICE_ID);
        loadData(serviceId);
        String saleDate = getIntent().getStringExtra(SALE_SERVICE_DATE);
        tvCreateData.setText(saleDate);
    }

    /**
     * 访问服务器获取售后数据
     * @param serviceId 售后服务id
     */
    private void loadData(String serviceId) {
        if (!RequestUtils.checkNetwork(MyApplication.getContext())) {
            return;
        }
        RequestUtils.findDetailById(serviceId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                handler.sendEmptyMessage(MSG_SERVER_ERROR);
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                saleServiceNetBean = responseBean.getEntity(SaleServiceNetBean.class);
                handler.sendEmptyMessage(MSG_SALE_SERVICE_DATA);
            }
        });
        RequestUtils.updateReply(serviceId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(ResponseBean responseBean) {

            }
        });
    }

    /**
     * 加载售后信息
     */
    private void showData() {
        List<ReplyNetBean> replies = saleServiceNetBean.getReplies();
        lvProblemMessageList.setAdapter(new SaleDetailAdapter(replies));
        tvProblemDesc.setText(saleServiceNetBean.getServiceContent());
        tvMacName.setText(saleServiceNetBean.getMacDto().getMacName());
        tvMacSealnum.setText(" - " + saleServiceNetBean.getMacDto().getSerialNum());

        String picPath = saleServiceNetBean.getPicPath();
        if (!TextUtils.isEmpty(picPath)) {
            String[] picPathList = picPath.split("&");
            for (String path : picPathList) {
                ImageView ivPic = new ImageView(SaleServiceDetailActivity.this);
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(DensityUtils.dp2px(this,
                        80), DensityUtils.dp2px(this, 80));
                ivPic.setLayoutParams(lp);
                ivPic.setScaleType(ImageView.ScaleType.FIT_XY);
                final String url = NetConfig.getRootUrl() + "download/downloadImage?fileName="
                        + path + "&rRange=0-";
                Picasso.with(this)
                        .load(url)
                        .config(Bitmap.Config.RGB_565)
                        .placeholder(R.drawable.pic_talkbox_sel)
                        .error(R.drawable.pic_talkbox_sel)
                        .into(ivPic);
                llPhotoContainer.addView(ivPic, 0);
                ivPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(SaleServiceDetailActivity.this, NetPicActivity
                                .class);
                        intent.putExtra(NetPicActivity.PIC_URL, url);
                        startActivity(intent);
                    }
                });
            }
        }
    }
}
